import { useState, useEffect } from 'react';
import { ServerInfo, ClientInfo } from "src/types"
import { List } from "antd"
import InfiniteScroll from 'react-infinite-scroller';
import { useNavigate } from 'react-router-dom';
function Home(): JSX.Element {

  const [serverInfo, setServerInfo] = useState<ServerInfo | null>(null);
  useEffect(() => {
    window.electron.ipcRenderer.on('update-server-info', (_event, server) => {
      console.log(server)
      setServerInfo(server);
    });

    return () => {
      window.electron.ipcRenderer.removeAllListeners('update-server-info');
    };
  }, []);

  let nav = useNavigate();
  const toDBShow = () => {
    nav("dbShow")
  }

  return (
    <div>

      <h1>主页面</h1>
      <button onClick={toDBShow}>跳转数据库页面</button>

      <div>服务器ip：{serverInfo?.ip}</div>
      <div>服务器端口：{serverInfo?.port}</div>
      <div>已连接客户端数量：{serverInfo?.clients.length}</div>
      <div>
        <h2>客户端信息：</h2>
        <div>
          {serverInfo ? (
            <div>
              {serverInfo.clients.length > 0 ? (
                <div className="demo-infinite-container">
                  <InfiniteScroll
                    initialLoad={false}
                    pageStart={0}
                    useWindow={false} >
                    <List
                      itemLayout="horizontal"
                      dataSource={serverInfo.clients}
                      renderItem={item => (
                        <List.Item>
                          <ItemView item={item} />
                        </List.Item>
                      )}
                    />

                  </InfiniteScroll>
                </div>
              ) : (
                <p>No clients connected.</p>
              )}
            </div>
          ) : (
            <p>Loading server information...</p>
          )}


        </div>
      </div>
    </div>
  );
}


const ItemView: React.FC<{ item: ClientInfo }> = ({ item }) => {
  return (
    <div className='flex flex-col text-white    '  >
      <div className=''>客户端id：{item.clientId}</div>
      <div>客户端ip：{item.ip}</div>
      <div>客户端发送：{item.sendMsg}</div>
      <div>客户端接收：{item.receiveMsg}</div>

    </div>
  );
}



export default Home;